package com.ry.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ry.novel.bean.AuthorHolder;
import com.ry.novel.bean.UserHolder;
import com.ry.novel.enums.NovelConst;
import com.ry.novel.exception.BusinessException;
import com.ry.novel.mapper.AuthorMapper;
import com.ry.novel.mapper.BookMapper;
import com.ry.novel.model.dto.AuthorInfo;
import com.ry.novel.model.dto.BookInfo;
import com.ry.novel.model.dto.condition.BookQuery;
import com.ry.novel.model.dto.condition.CommonQuery;
import com.ry.novel.model.entity.Author;
import com.ry.novel.service.AuthorService;
import com.ry.novel.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ry
 * @since 2022-01-25 14:43
 **/
@Service
public class AuthorServiceImpl implements AuthorService {
    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private BookService bookService;

    /**
     * 判断这个用户是否已经是作者
     *
     * @param userId
     * @return true是作者  false不是作者
     */
    @Override
    public AuthorInfo isAuthor(Long userId) {
        QueryWrapper<Author> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Author author = authorMapper.selectOne(wrapper);

        if (null == author){
            return null;
        }

        AuthorInfo authorInfo = new AuthorInfo();
        authorInfo.setId(author.getId());
        authorInfo.setUserId(author.getUserId());
        authorInfo.setPhone(author.getPhone());
        authorInfo.setPenName(author.getPenName());
        authorInfo.setState(author.getState());
        authorInfo.setCreateTime(author.getCreateTime());

        return authorInfo;
    }

    @Override
    public void toBeAuthor(AuthorInfo authorInfo) {
        if (null != isAuthor(UserHolder.userInfo.get().getId())){
            throw new BusinessException("此用户已经是作者");
        }
        Author entity = new Author();
        entity.setUserId(UserHolder.userInfo.get().getId());
        entity.setPhone(authorInfo.getPhone());
        entity.setPenName(authorInfo.getPenName());
        entity.setState(NovelConst.Author_STATE_NORMAL);
        entity.setCreateTime(LocalDateTime.now().toString());

        authorMapper.insert(entity);
    }

    @Override
    public Page<BookInfo> authorHome(CommonQuery commonQuery) {
        //根据作者id查询小说
        Page<BookInfo> bookInfoPage = bookService.queryByAuthorId(commonQuery);

        return bookInfoPage;
    }
}
